﻿using System;
using UnityEngine;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using QRCoder;
using QRCoder.Unity;

namespace ZyGame
{
    public static class StringExtension
    {
        private static int rep = 0;

        public static Sprite GenericSprite(this string data)
        {
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(data, QRCodeGenerator.ECCLevel.Q);
            UnityQRCode qrCode = new UnityQRCode(qrCodeData);
            Texture2D qrCodeAsTexture2D = qrCode.GetGraphic(pixelsPerModule: 10);
            qrCodeAsTexture2D.filterMode = FilterMode.Point;
            var qrCodeSprite = Sprite.Create(qrCodeAsTexture2D, new Rect(0, 0, qrCodeAsTexture2D.width, qrCodeAsTexture2D.height), new Vector2(0.5f, 0.5f), 100f);
            return qrCodeSprite;
        }

        public static bool EnsureResponseStatusCode(this JObject data)
        {
            if (data["status"].ToString() is not "100")
            {
                Client.Window.Toast(data["message"].ToString());
                return false;
            }
            return true;
        }

        public static Type GetTypeWithStringName(this string name)
        {
            switch (name)
            {
                case "int": return typeof(int);
                case "float": return typeof(float);
                case "double": return typeof(double);
                case "string": return typeof(string);
                case "bool": return typeof(bool);
                case "uint": return typeof(uint);
                case "long": return typeof(long);
                case "ulong": return typeof(ulong);
                case "byte": return typeof(byte);
            }
            return typeof(object);
        }

        public static bool IsValidEmail(this string email)
        {
            if (string.IsNullOrWhiteSpace(email))
                return false;
            try
            {
                return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase);
            }
            catch (RegexMatchTimeoutException)
            {
                return false;
            }
        }

        public static string GenerateCheckCode(int codeCount)
        {
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + rep;
            rep++;
            System.Random random = new System.Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }

        public static JObject GetJObject(this string value)
        {
            return JObject.Parse(value);
        }

        public static T Deserialied<T>(this string value)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
        }

        public static string ToJson(this object data) => Newtonsoft.Json.JsonConvert.SerializeObject(data);

        public static string GetElementAssetBundlePath(this string path)
        {
            string url = path;
            url = url.Substring(0, url.LastIndexOf('/'));
            url = url.Substring(0, url.LastIndexOf('/'));
            return $"{url}/{AppConfig.GetPlatformName().ToLower()}/{Path.GetFileName(path)}";
        }

        public static string NormalPath(this string path)
        {
            return path.Replace("\\", "/");
        }

        public static string GetFolder(this string path, int childIndex)
        {
            path = path.NormalPath();
            string[] folders = path.Split('/');
            if (childIndex >= folders.Length)
            {
                return string.Empty;
            }
            return folders[childIndex];
        }

        public static string Sha256(this string value)
        {

            using var hmacsha256 = SHA256.Create();
            byte[] hashmessage = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(value));
            string hashString = string.Empty;
            foreach (byte x in hashmessage)
            {
                hashString += String.Format("{0:x2}", x);
            }
            Client.Console.WriteLine("org:" + value + " sha256:" + hashString);
            return (hashString);
        }
        public static bool TryGetJson<T>(this string text, out T data)
        {
            try
            {
                data = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(text);
                return true;
            }
            catch (Exception e)
            {
                Client.Console.WriteError(e);
                data = default;
                return false;
            }
        }

        public static bool IsNullOrEmpty(this string target)
        {
            return string.IsNullOrEmpty(target);
        }

        public static string GetMd5(this string info)
        {
            return Encoding.UTF8.GetBytes(info).GetMd5();
        }

        public static Color ToColor(this string hex)
        {
            hex = hex.Replace("0x", string.Empty);
            hex = hex.Replace("#", string.Empty);
            hex = hex.Replace("O", "0");
            hex = hex.Replace("o", "0");
            byte a = byte.MaxValue;
            byte r = byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
            byte g = byte.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
            byte b = byte.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);
            if (hex.Length == 8)
            {
                a = byte.Parse(hex.Substring(6, 2), NumberStyles.HexNumber);
            }

            return new Color32(r, g, b, a);
        }

        public static Color[] ToColors(this string str)
        {
            string[] s = str.Split(',');
            Color[] colors = new Color[s.Length];
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i].StartsWith("0x"))
                {
                    colors[i] = s[i].ToColor();
                }
            }
            return colors;
        }
    }
}